<?php



namespace StudyBuddy\Controllers;


use \StudyBuddy\WebPage;
use \StudyBuddy\Request;
use \StudyBuddy\Responder;
use \StudyBuddy\FollowManager;

/**
 * This controller is responsible
 * for processing the Follow request
 * 
 * Follow request can be for Tag, User or Question
 *
 */
class Follow extends WebPage
{
	protected $requireToken = true;

	protected $bRequirePost = true;

	protected $aRequired = array('f', 'ftype', 'follow');

	protected $oFollowManager;

	protected function main(){

		$this->oFollowManager = new FollowManager($this->oRegistry);

		$this->processFollow()
		->returnResult();
	}


	protected function processFollow(){
		$type = $this->oRequest['ftype'];
		$follow = $this->oRequest['follow'];
		$f = $this->oRequest['f'];

		switch(true){

			case ('q' === $type):
				if('off' === $follow){
					$this->oFollowManager->unfollowQuestion($this->oRegistry->Viewer, (int)$f);
				} else {
					$this->oFollowManager->followQuestion($this->oRegistry->Viewer, (int)$f);
				}

				break;

			case ('t' === $type):
				if('off' === $follow){
					$this->oFollowManager->unfollowTag($this->oRegistry->Viewer, $f);
				} else {
					$this->oFollowManager->followTag($this->oRegistry->Viewer, $f);
				}

				break;

			case ('u' === $type):
				if('off' === $follow){
					$this->oFollowManager->unfollowUser($this->oRegistry->Viewer, (int)$f);
				} else {
					d('following user '.$f);
					$this->oFollowManager->followUser($this->oRegistry->Viewer, (int)$f);
				}

				break;
		}

		return $this;
	}


	/**
	 * Return empty array via Ajax
	 * this way UI will not have to do anything
	 *
	 *
	 */
	protected function returnResult(){
		if(Request::isAjax()){
			Responder::sendJSON(array());
		}

		Responder::redirectToPage();
	}
}
